<?php
class CategoryModel extends Model{
	public $table = 'category';
	public $validate=array(
			array('cname','nonull','栏目名不能为空',2,3),
			array('pid','checkPid','栏目不存在',2,3)
		);
	public $model;
	public function __init(){

		$this->model = M('category');
	}
	public function checkPid($name,$pid,$msg){
		$pid = intval($pid);
		if($pid===0)return true;
		$category = catched('category');
		if(isset($category[$pid])){
			return true;
		}else{
			return $msg;
		}
		
	}

	
	public function addCategory(){
		if($this->create()){
			if($this->model->add()){
				$this->updateCache();
				return true;
			}else{
				$this->error='栏目添加失败';
				return false;
			}
		}else{
			$this->error='参数错误，栏目添加验证失败';
			return false;
		}
	}
	//更新栏目
	public function saveCategory(){
		if($this->create()){
			if($this->model->where(array('cid'=>Q('cid')))->save()){
				$this->updateCache();
				return true;
			}else{
				$this->error = '栏目更新失败';
			}
		}
	}
//对缓存数据进行处理，将cid作为数组的索引值
	public function updateCache(){
		$catModel = M('category');
		$catData = $catModel->all();
		$reData = array();
		if(!empty($catData)){
			foreach ($catData as $key => $c) {
				$reData[$c['cid']]=$c;
			}
		}
		$reData = Data::tree($reData,'cname');		
		return catched('category',$reData);
	}
}
?>
